<template>
  <div class="login_container">
    <!-- 顶部内容 -->
    <el-row class="top_ys">
      <el-col :xs="2" :sm="2" :md="2" :lg="1" :xl="1">
        <div class="logo_ys">
          <img src="../../assets/img/logo.png" />
        </div>
      </el-col>
      <el-col :xs="22" :sm="22" :md="22" :lg="23" :xl="23">
        <div class="title_ys">
          <h2>崇明教育<span>单点登录认证系统</span></h2>
        </div>
      </el-col>
    </el-row>
    <!-- 登录内容 -->
    <div class="login_main">
      <!-- <el-tabs v-model="activeName">
        <el-tab-pane label="账户密码登录" name="first"> -->
      <el-form ref="loginFormRef" :model="cmeduLoginForm" :rules="cmeduLoginFormRules" class="login_form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="cmeduLoginForm.username" prefix-icon="el-icon-user" placeholder="请输入用户名"
            clearable></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <!-- <el-input :type="flagType" v-model="cmeduLoginForm.password" prefix-icon="el-icon-lock" placeholder="请输入密码">
            <i slot="suffix" :class="[
              this.flag
                ? 'iconfont icon-xianshimima'
                : 'iconfont icon-buxianshimima',]" @click="getFlag()"></i>
          </el-input> -->
          <el-input placeholder="请输入密码" v-model="cmeduLoginForm.password" prefix-icon="el-icon-lock"
            show-password></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="logincode">
          <el-input class="w68" placeholder="请输入验证码" clearable v-model="cmeduLoginForm.logincode"></el-input> <img
            class="w32" @click="getNumber" :src="imgNumber" />
        </el-form-item>
        <!-- 选择框 -->
        <el-form-item>
          <el-checkbox v-model="checked">记住密码</el-checkbox>
          <a @click="dialogForgetVisible = true" class="forget_pass">忘记密码</a>
        </el-form-item>
        <el-button type="primary" :loading="loading" class="btn_size" @click="login"
          @keyup.enter="keyDown">登录</el-button>
      </el-form>
      <div class="login_other">
        <div class="line"><span class="font_location"><span class="cirle1"></span>其他登录方式<span
              class="cirle2"></span></span></div>
        <div>
          <a href="javascript:;" v-for="(item, i) in imgIcon">
            <img class="icon" :title="item.providerName" :src="`../../${item.icon}`" @click="skipThirdLogin(i)" />
          </a>
          <!--          <a href="javascript:;"><img src="../../assets/img/wechat.png" /></a>-->
          <!--          <a href="javascript:;"><img src="../../assets/img/dingtalk.png" /></a>-->
          <!--          <a href="javascript:;"><img src="../../assets/img/wechat_enterprise.png" /></a>-->
        </div>
      </div>
      <!-- </el-tab-pane>
      </el-tabs> -->
    </div>
    <!-- 底部内容 -->
    <div class="footer_ys">
      <h5>
        Copyright© 2023 上海市崇明区教育局<a href="https://home.cmjy.sh.cn" target="_blank">https://home.cmjy.sh.cn</a>
      </h5>
    </div>
    <!-- 忘记密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="dialogForgetVisible" class="w60">
      <!-- 内容主体区域 -->
      <el-form :model="editPasswordForm" :rules="editPasswordFormRules" ref="editPasswordFormRef">
        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="editPasswordForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="mobilecode">
          <el-input class="w68" placeholder="请输入手机验证码" v-model="editPasswordForm.mobilecode"></el-input><el-button
            class="w32"></el-button>
        </el-form-item>
        <el-form-item label="新密码：" prop="newpassword">
          <el-input :type="flagType" v-model="editPasswordForm.newpassword" placeholder="请输入密码">
            <i slot="suffix" :class="[
        this.flag
          ? 'iconfont icon-xianshimima'
          : 'iconfont icon-buxianshimima',]" @click="getFlag()"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForgetVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogForgetVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import store from '@/store'
import userLogin from "@/api/login";
import userStore from "@/store/modules/user"
import { useRoute, useRouter } from "vue-router";
export default {
  data() {
    // 验证手机号的正则表达式
    const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
    // 验证方法
    const validatorMobile = function (mobile, value, callback) {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      flag: false,
      appInfo: "",
      imgIcon: "",
      captcha: "",
      imgNumber: "",
      state: "",
      flagType: 'password',
      cmeduLoginForm: {
        username: '',
        password: '',
        logincode: '',
      },
      // 用户登录的验证规则对象
      cmeduLoginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 100,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          {
            min: 3,
            max: 30,
            message: '长度在 3 到 30 个字符',
            trigger: 'blur',
          },
        ],
        logincode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, message: '长度在 4 个字符', trigger: 'blur' },
        ],
      },
      activeName: 'first',
      checked: true,
      // 控制忘记密码对话框显示与隐藏
      dialogForgetVisible: false,
      // 修改密码的表单数据
      editPasswordForm: {
        mobile: '',
        mobilecode: '',
        newpassword: ''
      },
      // 修改密码的验证规则对象
      editPasswordFormRules: {
        mobile: [
          { required: true, validator: validatorMobile, trigger: 'blur' }
        ],
        mobilecode: [
          { required: true, message: '请输入手机验证码', trigger: 'blur' },
          { min: 4, max: 15, message: '新密码的长度在4个字符之间', trigger: 'blur' }
        ],
        newpassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '新密码的长度在6-15个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getNumber();
    this.thirdLogin();
    window.addEventListener('keydown', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    getFlag() {
      this.flag = !this.flag
      this.flagType = this.flag ? 'text' : 'password'
    },

    thirdLogin() {
      userLogin.thirdLogin(true, "").then((res) => {
        if (res.code == 0) {
          this.imgIcon = res.data.socials.providers;
          this.appInfo = res.data.socials.providers;
        }
      });
    },
    skipThirdLogin(val) {
      console.log(this.appInfo[val].provider)
      let provider = this.appInfo[val].provider;
      userLogin.goThirdLogin(provider).then((res) => {
        console.log(res)
        if (res.code == 0) {
          // this.$router.push({ path: "/callback/" + provider })
          window.location.href = res.data;
        }
      });
    },
    getNumber() {
      this.getInitKey();
    },
    async getInitKey() {
      await userLogin.getInitKey().then(res => {
        this.state = res.data.state
        userLogin.getNumber({ state: res.data.state }).then(res => {
          this.imgNumber = res.data.image
        });
      });
    },
    async login() {
      // console.log("登录了2024314");
      this.loading = true;
      const data = {
        username: this.cmeduLoginForm.username,
        password: this.cmeduLoginForm.password,
        captcha: this.cmeduLoginForm.logincode,
        state: this.state,
        authType: "normal",


      }
      await this.$refs.loginFormRef.validate(valid => {
        if (!valid) return
        userLogin.login_signin(data).then(res => {
          console.log(res);
          if (res.data) {

            let token = res.data.token;
            Cookies.set("congress", res.data.token, { expires: 1 })
            Cookies.set("online_ticket", res.data.ticket, { expires: 1 })
            Cookies.set("token", res.data.token, { expires: 1 })
            Cookies.set("admin-token", res.data.token, { expires: 1 })
            Cookies.set("admin_token", res.data.token, { expires: 1 })

            userLogin.getUserInfo().then(res => {
              // console.log(res);
              this.$store.dispatch("user/saveUserInfo", res.data)
            })
            this.loading = false;
            userLogin.getisAlter().then(res => {
              console.log(res);
              if (res == 1) { //判断 isAlter 是否修改用户名 1已修改正常 走逻辑登录
                this.$router.replace({
                  path: this.$route.query.redirect
                    ? this.$route.query.redirect : "/"
                })
              } else {//0未修改需要鉴权修改
                console.log("未修改需要鉴权修改");
                this.$message.warning('未认证，请先认证', 3)
                this.$router.push({ path: '/authenticaUser' })
              }
            })
          } else {
            this.loading = false;
            this.getNumber();
            this.$message.error(res.message, 2)
          }
        }).catch(error => {
          this.loading = false;
          this.$message.warning('密码错误', 2)
        });


      })
    },
    keyDown(e) {
      let key = null;
      if (window.event === undefined) {
        key = e.keyCode;
      } else {
        key = window.event.keyCode;
      }
      if (key === 13) {
        this.login();
      }
    },
  }
}
</script>

<style lang="less" scoped>
.logo_ys {
  text-align: center;

  img {
    vertical-align: middle;
  }
}

.title_ys {
  h2 {
    margin: 0;
    letter-spacing: 2px;
  }
}

.login_form {
  padding: 16px;
}

.w68 {
  width: 68%;
}

.w32 {
  float: right;
  width: 31%;
}

.footer_ys {
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  text-align: center;

  h5 {
    margin: 0;
    height: 30px;
    line-height: 12px;
    font-weight: 300;
  }

  h5 a {
    padding-left: 8px;
  }
}

.btn_size {
  width: 100%;
}

.captcha-ys {
  width: 100%;
  height: 100%;
}

.login_other {
  position: relative;
  margin: 8px 16px 0 16px;
  font-size: 14px;
  box-sizing: border-box;

  div::before {
    display: block;
    content: '';
    width: 100%;
    height: 1px;
    background-color: #DCDFE6;
  }

  div {
    text-align: center;

    span {
      display: inline-block;
      position: absolute;
      top: -10px;
      background-color: #fff;
    }

    span.cirle1 {
      left: -6px;
      top: 6px;
      width: 8px;
      height: 8px;
      border: 1px solid #DCDFE6;
      border-radius: 50%;
      z-index: 1;
    }

    .font_location {
      left: 50%;
      padding: 0 12px;
      color: #C4BFBF;
      transform: translateX(-50%);
    }

    span.cirle2 {
      right: -6px;
      top: 6px;
      width: 8px;
      height: 8px;
      border: 1px solid #DCDFE6;
      border-radius: 50%;
      z-index: 1;
    }
  }

  img {
    width: 32px;
    height: auto;
    vertical-align: middle;
    margin: 16px;
  }
}

.forget_pass {
  float: right;
  text-decoration: none;
  color: #5b5b5d;
  cursor: pointer;
}
</style>
